package com.czh.wx.controller;

import com.czh.wx.constants.WxConstant;
import com.czh.wx.handler.WxMsgFactory;
import com.czh.wx.handler.WxMsgHandler;
import com.czh.wx.utils.MessageUtil;
import com.czh.wx.utils.SHA1;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Objects;

/**
 * @author caozaihui
 * @version 1.0
 * @since 2024/9/1 下午 7:26
 */
@RestController
@RequestMapping("/wx/")
@Slf4j
public class CallBackController {

    @Resource
    private WxMsgFactory wxMsgFactory;


    /**
     * 检验消息是否来自微信服务器
     *
     * @return java.lang.String
     * @since 2024/9/2 上午 9:28
     */
    @GetMapping("callback")
    public String callback(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr) {
        log.info("get验签请求参数：signature:{}，timestamp:{}，nonce:{}，echostr:{}",
                signature, timestamp, nonce, echostr);
        String shaStr = SHA1.getSHA1(WxConstant.token, timestamp, nonce);
        if (signature.equals(shaStr)) {
            return echostr;
        }
        return "unknown";
    }

    /**
     * 接收消息
     *
     * @return java.lang.String
     * @since 2024/9/2 上午 9:29
     */
    @PostMapping(value = "callback", produces = "application/xml;charset=utf-8")
    public String callback(@RequestBody String requestBody,
                           @RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam(value = "msg_signature", required = false) String msgSignature) {
        log.info("post验签请求参数：timestamp:{}，nonce:{}，echostr:{}",
                signature, timestamp, nonce);
        log.info(requestBody);
        Map<String, String> requestMap = MessageUtil.parseXml(requestBody);
        String msgType = requestMap.get(WxConstant.XMLNODE_MsgType);
        String event = requestMap.get(WxConstant.XMLNODE_Event);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(msgType);
        if (Objects.nonNull(event)) {
            stringBuilder.append(".").append(event);
        }
        WxMsgHandler handlerByMsgType = wxMsgFactory.getHandlerByMsgType(String.valueOf(stringBuilder));
        if (Objects.isNull(handlerByMsgType)) {
            return "unknown";
        }
        return handlerByMsgType.dealMsg(requestMap);
    }
}
